#include "person.h"
#include <stdio.h>

// 实现虚函数表
PersonVTable Person_vtable = {
    .speak = Person_speak,
    .to_string = Person_to_string
};

IMPLEMENT_CLASS(Person, Object)


void Person_destroy_impl(Person* self){
    if(self->name != NULL)
        free(self->name);
    free(self);
    printf("Free !\n");
}
// 具体方法实现
void Person_speak(Person* self) {
    printf("Hello, my name is %s and I'm %d years old.\n", 
           self->name ? self->name : "Unknown", self->age);
}

char* Person_to_string(Person* self) {
    int needed = snprintf(NULL, 0, "Person{name: %s, age: %d}", 
                         self->name ? self->name : "NULL", self->age) + 1;
    char* result = malloc(needed);
    snprintf(result, needed, "Person{name: %s, age: %d}", 
             self->name ? self->name : "NULL", self->age);
    return result;
}

void Person_set_name(Person* self, const char* name) {
    if (self->name) free(self->name);
    self->name = name ? strdup(name) : NULL;
}

void Person_set_age(Person* self, int age) {
    self->age = age;
}